package com.zyh.pool;

import java.util.concurrent.*;

/**
 * @Author zyh
 * @Date 2024/8/12 10:42
 * @Description Runnable 和 Callable
 */

public class ThreadPoolDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //Runnable
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "正在执行");
            }
        };
        //通过线程池提交
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<String> result = threadPool.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "正在执行");
            }
        }, "xixi");//可以自己写一个返回值，但是返回值不能在run中参与运算
        System.out.println(result.get());
        /*
            Callable
         */
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "正在执行");
                int num = 10;
                return num % 3;//返回值可以是call中的运算结果
            }
        };
        //Thread thread = new Thread(callable);
        //通过线程池来提交
        ExecutorService threadPool1 = Executors.newSingleThreadExecutor();
        //获得Future对象
        Future submit = threadPool1.submit(callable);
        //获取返回值
        Object o = submit.get();
        System.out.println(o);
        threadPool.shutdown();
        threadPool1.shutdown();
    }
}
